@extends('layouts.header')
@section('style')
    .check-box {
    padding-left: 18px;
    padding-right: 0px;
    padding-top: 0px;
    padding-bottom: 0px;
    }
@endsection
@section('content')
    <nav class="breadcrumb"><i class="Hui-iconfont">&#xe67f;</i> 首页
        <span class="c-gray en">&gt;</span> 检测业务
        <span class="c-gray en">&gt;</span> <a onclick="location.href='/{{config('constant.name_admin')}}/contract/indexResLuru';">结果录入</a>
        <span class="c-gray en">&gt;</span> 点击进入【{{ $contractInfo->client_name }}】

        <a class="btn btn-primary radius r" style="line-height:1.6em;margin-top:3px" href="javascript:location.replace(location.href);" title="刷新"><i class="Hui-iconfont">&#xe68f;</i></a>
        <a class="btn btn-primary radius r mr-10" style="line-height:1.6em;margin-top:3px" href="/{{config('constant.name_admin')}}/contract/indexResLuru"> <i class="Hui-iconfont Hui-iconfont-arrow1-left"></i>&nbsp;&nbsp;返回
        </a>
    </nav>
    <div class="page-container">
        <div class="cl pd-5 bg-1 bk-gray mt-10">
            <span class="l">
                <a class="btn btn-primary radius" href="javascript:;" onclick="submit_batch()">批量提交</a>
                <a class="btn btn-primary radius" href="javascript:;" id="luru-batch">批量录入</a>
                <a class="btn btn-primary radius" href="javascript:;" id="luru-date">批量录入试验日期</a>
                <a class="btn btn-primary radius" href="javascript:;" onclick="download_original({{ $contractInfo->id }},1)"><i class="Hui-iconfont">&#xe640;</i> 原始记录</a>
            </span>
        </div>
        <div class="mt-10">
            <table class="table table-border table-bordered table-bg table-hover table-responsive" id="datatable">
                <thead>
                <tr class="text-c">
                    <th> <input type="checkbox" id="checkAll"> </th>
                    <th>条形码</th>
                    <th>样品名称</th>
                    <th>额定电压</th>
                    <th>样品状态</th>
                    <th>结论</th>
                    <th style="width: 100px;">不合格照片</th>
                    <th>状态</th>
                    <th>试验日期</th>
                    <th>操作</th>
                </tr>
                </thead>
            </table>
            <div class="f-r mt-10"><input class="input-text" type="text" value="" placeholder="指定页码" id="jumpPage"/></div>
        </div>

        {{-- <div class="cl pd-5 bg-1 bk-gray mt-15">
                <input type="button" value="确定" id="btn_ok" class="btn btn-success radius">
        </div> --}}
    </div>

    <!--请在下方写此页面业务相关的脚本-->
    <script type="text/javascript" src="/admin/lib/jquery.mousewheel.min.js"></script>
    <script type="text/javascript" src="/admin/static/myfolder/js/imgopreate.js?ver={{config('constant.static_res_ver')}}"></script>
    <script type="text/javascript">
        var table, nophonotext = '未上传不合格照', index2, isup = 0;

        $(function () {

            /*  $('.skin-minimal input').iCheck({
                 checkboxClass: 'icheckbox-blue',
                 radioClass: 'iradio-blue',
                 increaseArea: '100%'
             }); */

            // $.fn.dataTable.ext.errMode = 'throw';//datatable抛异常的方式，在console中输出，默认以alert的方式弹出
            table = $('#datatable').DataTable({
                order: [[1, 'asc']],//默认第几个排序
                pageLength: 10,
                // "dom": '<"toolbar f-l pb-15">frtip',
                // "lengthChange": false,
                // "stateSave": true,// 状态保存 - 再次加载页面时还原表格状态
                // "stateDuration": -1,//仅保留当前会话的数据
                // "paging":false, //禁用分页
                serverSide: false,//服务器端处理模式——此模式下如：过滤、分页、排序的处理都放在服务器端进行。
                // responsive: true,//响应式，需要插件
                // fixedHeader: true,//表头固定，需要插件
                // autoWidth: false,
                ajax: "{{url()->full()}}",
                processing: true,//加载数据时候是否显示进度条
                language: {url: '/admin/lib/datatables/dataTables_Chinese_Lang.json'},
                initComplete: function (settings, json) {
                    //当表格完成加载绘制完成后执行此方法
                    //仅初次表格数据加载完成后执行
                    // $(row).addClass( 'text-c' );
                    $('#datatable_filter label input').attr('placeholder', '样品名称/条形码')
                },
                columns: [
                    { //复选框
                        data: null, class: "text-c",
                        render: function (data, type, row, meta) {
                            if (row.jielun == 0 || row.status == 1) {
                                return '';
                            } else {
                                return '<input type="checkbox" value="' + row.id + '">';
                            }
                        }, searchable: false, orderable: false
                    },
                    {data: "bar_code", class: "text-c"},
                    {data: "contract_gaiyao.tool_name", class: "text-c"},
                    {data: "contract_gaiyao.voltage", class: "text-c", searchable: false, orderable: false},//voltage
                    {data: "sample_status", class: "text-c", searchable: false, orderable: false},
                    {
                        data: "res", class: "text-c",
                        render: function (data, type, row, meta) {
                            if (data == 0) {
                                return '';
                            } else if (data == 1) {
                                return '<span class="label label-primary radius">合格</span>';
                            } else if (data == 2) {
                                return '<span class="label label-danger radius">不合格</span>';
                            }
                        }
                    },
                    {
                        data: 'non_photo', class: "text-c",
                        render: function (data, type, row, meta) {
                            let str = '<div id="non-photo-' + row.id + '">';
                            let imgstr = '<img style="width:100%;" class="img-responsive radio" src="' + data + '?' + '{{time()}}' + '" onclick="biggerimg(this)">' +
                                '<a onclick="imgdel(' + row.bar_code + ',this)" class="ml-5 btn btn-danger-outline radius size-MINI">删除</a>';
                            str += (row.res == 2 ? data === '' ? nophonotext : imgstr : '/');
                            str += '</div>';
                            return str;
                        }, searchable: false, orderable: false
                    },
                    {
                        data: "status0", class: "text-c",
                        render: function (data, type, row, meta) {
                            // -1-被驳回，0-未提交，1-已提交，2-审核通过，3-未试验，4-试验中
                            if (data == -1) {
                                return '<span class="label label-danger radius">被驳回</span>';
                            } else if (data == 0) {
                                return '<span class="label label-primary radius">未提交</span>';
                            } else if (data == 1) {
                                return '<span class="label label-default radius">已提交</span>';
                            } else if (data == 2) {
                                return '<span class="label label-success radius">审核通过</span>';
                            } else if (data == 3) {
                                return '<span class="label label-success radius">未试验</span>';
                            } else if (data == 4) {
                                return '<span class="label label-success radius">试验中</span>';
                            } else {
                                return '<span class="badge badge-default radius">未知状态</span>';
                            }
                        }
                    },
                    {data: "test_time", class: "text-c"},
                    {
                        data: null, class: "text-c",
                        render: function (data, type, row, meta) {
                            var str = '<div class="f-l">' +
                                '<a class="btn btn-primary-outline radius size-MINI" href="javascript:;" onclick="testData_edit(\'结果录入\',\'/{{config('constant.name_admin')}}/itemData/index\',' + row.id + ',$(window).width() - 200)">结果录入</a>';
                            if (row.status >= 1) {
                                str += '<a class="ml-5 btn radius size-MINI disabled" href="javascript:;">提交</a>';
                            } else {
                                str += '<a class="ml-5 btn btn-primary-outline radius size-MINI" href="javascript:;" onclick="submit_one(' + row.id + ')">提交</a>';
                            }
                            if (row.res == 2) {
                                str += '<a class="ml-5 btn btn-primary-outline radius size-MINI" href="javascript:;" onclick="uploadnonimg(' + row.id + ',' + row.bar_code + ')">上传不合格照片</a>';
                            }
                            if (row.status0 === -1) {
                                str += '<a class="ml-5 btn btn-danger radius size-MINI" href="javascript:;" onclick="show_baklog(' + row.id + ')">驳回原因</a>';
                            }
                            str += '<a class="ml-5 btn btn-primary radius size-MINI" href="javascript:;" onclick="download_original(' + row.id +')"><i class="Hui-iconfont">&#xe640;</i>原始记录</a>';
                            str += '</div>';
                            return str;
                        }, searchable: false, orderable: false
                    },
                ]
            });
            /*  draw  在表格完成绘制后触发*/
            table.on('draw', function () {

                /*         var info = table.page.info();
                        //如果最后一页仅剩一条记录，而且不是在第一页
                        if((info.start == info.end) && info.end > 1){
                            //跳转到上一页
                            $('#datatable_previous').click();
                        } */
                $('.skin-minimal input').iCheck({
                    checkboxClass: 'icheckbox-blue',
                    radioClass: 'iradio-blue',
                    increaseArea: '20%'
                });

                //清除table中 CheckBox的对勾
                $("#datatable").find("input[type=checkbox]").iCheck('uncheck');

                iCheck_checkAll();//iCheck 全选
            });


        });

        /*批量录入*/
        $('#luru-batch').on('click',function () {
            layer_show('批量录入',"/{{config('constant.name_admin')}}/contractGaiyao/resLuru/{{request('id')}}",800);
        })

        /*批量录入试验日期*/
        $('#luru-date').on('click',function () {
            if($('tbody input:checkbox:checked').length == 0){
                layer.msg('请选择要修改的样品！');
                return false;
            }
            var html = "<div class='ml-20'><input id='pi_date' class='mt-10' type='date' /></div>";
            var indexDate = layer.open({
                type: 1,
                offset: 'auto',
                area: ['300px', '300px'],
                title: "批量录入试验日期", //不显示标题
                content: html, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                btn: ['提交', '取消'],
                yes: function (index, layero) {
                    var sample_ids = [];
                    $('tbody input:checkbox:checked').each(function(index){
                        sample_ids.push($(this).val());
                    })
                    let params = {
                        editDate:1,
                        date:$('#pi_date').val(),
                        sample_ids:sample_ids,
                        _token: '{{csrf_token()}}',
                        _form_token:"{{csrf_form_token()}}"
                    };
                    ajax('post','',params,luruDateRes,0);
                    function luruDateRes(res) {
                        if(res == 0){
                            layer.msg('操作失败！',{icon:2,time:1000},function (){
                                window.location.reload()
                            });
                        }else{
                            let cha = $('tbody input:checkbox:checked').length - parseInt(res);
                            if(cha == 0){
                                layer.msg('操作成功！',{icon:1,time:1000},function (){
                                    window.location.reload()
                                });
                                layer.close(indexDate);
                                table_reload(false);
                            }else{
                                layer.confirm('有'+res+'条数据的检测日期修改失败！',{icon:2,time:1000},function (){
                                    window.location.reload()
                                });
                            }
                        }
                    }
                },
                cancel: function () {
                    //右上角关闭回调
                }
            });
        })

        /*试验数据  修改*/
        function testData_edit(title, url, id, w, h) {
            layer_show(title, url + '?id=' + id, w, h);

        }

        /*表格重新加载*/
        function table_reload(bool) {
            if (bool) {
                //true时，跳到第一页
                table.ajax.reload();
            } else {
                //false时，停留在原来页
                table.ajax.reload(null, false);
            }
        }

        /*单个提交*/
        function submit_one(id) {

            $.ajax({
                type: 'post',
                url: '/{{config('constant.name_admin')}}/sampleInfo/oneSubmit',
                // dataType: 'json',
                data: {
                    id: id,
                    batch_id: '{{ $_GET['id'] }}',
                    _token: '{{ csrf_token() }}',
                    _form_token : ' {{csrf_form_token()}} '
                },
                success: function (data) {
                    // console.log(data);
                    if (data === '1') {
                        table_reload(0);//0停留在当前页，1回到第一页
                        layer.msg('提交成功!', {icon: 1, time: 1000});
                    } else if (data === '2') {
                        layer.msg('结果未全部录入，不能提交!', {icon: 2, time: 2000});
                    } else if (data === '0') {
                        layer.msg('提交失败!', {icon: 2, time: 2000});
                    } else {
                        layer.msg(data, {icon: 2, time: 2000});
                    }
                    res_func()
                },
                error: function (data) {
                    // console.log(data);
                    ajax_error(data);
                    res_func()
                },
                beforeSend: function () {
                    //0.4透明度 白色遮罩
                    index2 = layer.load(2, {shade: [0.05, '#000']});
                },
                complete: function () {
                    layer.close(index2);
                },
            });
        }

        /*批量提交*/
        function submit_batch() {
            var doms = $("tbody tr > td:first-child input:checkbox:checked");
            var l = doms.length;
            if (l == 0) {
                layer.msg('请先勾选一条记录', {time: 2000});
                return;
            }

            var checkID = [];//定义一个空数组
            doms.each(function (i) {//把所有被选中的复选框的值存入数组
                checkID[i] = $(this).val();
            });

            var index2;
            layer.confirm('您勾选了 ' + l + ' 条记录<br>确定要批量提交吗？', {title: '询问', icon: 3}, function (index) {
                $.ajax({
                    type: 'post',
                    url: '/{{config('constant.name_admin')}}/sampleInfo/batchSubmit',
                    // dataType: 'json',
                    data: {
                        checkID: checkID,
                        batch_id: '{{ $_GET['id'] }}',
                        _token: '{{ csrf_token() }}',
                        _form_token : ' {{csrf_form_token()}} '
                    },
                    success: function (data) {
                        table_reload(0);//0停留在当前页，1回到第一页
                        layer.msg(data, {icon: 6, time: 3000});
                        res_func()
                    },
                    error: function (data) {
                        ajax_error(data);
                        res_func()
                    },
                    beforeSend: function () {
                        //0.4透明度 白色遮罩
                        index2 = layer.load(2, {shade: [0.05, '#000']});
                    },
                    complete: function () {
                        layer.close(index2);
                    },
                });
            });
        }

        //因为每次提交以后token都失效了。需要刷新页面重新获取
        function  res_func(){
            setTimeout(function (){
                window.location.reload()
            },2000)
        };
        /*删除*/
        function del(id) {
            var index2;

            layer.confirm('确认要删除吗？', function (index) {
                $.ajax({
                    type: 'GET',
                    url: '/{{config('constant.name_admin')}}/client/del' + '?id=' + id,
                    // dataType: 'json',
                    success: function (data) {
                        // console.log(data);
                        if (data === '1') {
                            table_reload(0);//0停留在当前页，1回到第一页
                            layer.msg('删除成功!', {icon: 1, time: 2000});
                        } else {
                            layer.msg('删除失败!', {icon: 2, time: 2000});
                        }
                    },
                    error: function (data) {
                        ajax_error(data);
                    },
                    beforeSend: function () {
                        //0.4透明度 白色遮罩
                        index2 = layer.load(2, {shade: [0.05, '#000']});
                    },
                    complete: function () {
                        layer.close(index2);
                    },
                });
            });
        }

        /*编辑*/
        function edit(title, url, id, w, h) {
            layer_show(title, url + '?id=' + id, w, h);
        }

        /*添加*/
        function add(title, url, w, h) {
            layer_show(title, url, w, h);
        }

        /*上传不合格照片*/
        function uploadnonimg(id, bar_code) {
            var imgHtml = "<div class='ml-20'><input accept='image/*' class='mt-10' type='file' onclick='upimg()'/><br>" +
                "<span style='color:red;'>要求：</span>图片宽高比为4:3或3:4（建议直接用手机拍摄4:3图片，如果需要再用imark或小Q画笔对图片进行局部放大）<br>" +
                "<p class='ml-50'>上传图片预览：</p><div class='text-c'><img class='img-responsive fornonphoto' style='height:300px;' src='' onclick='biggerimg(this)'></div>" +
                "</div>";
            layer.open({
                type: 1,
                offset: 'auto',
                area: ['600px', '600px'],
                title: "上传不合格照片", //不显示标题
                content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                btn: ['提交', '取消'],
                yes: function (index, layero) {
                    if (isup === 0) {
                        layer.msg('图片不符合要求，请重新上传');
                        return false;
                    }
                    let base64data = $('.fornonphoto').attr('src');
                    if (base64data === '') {
                        layer.alert('请先上传新的不合格照');
                        return false;
                    }
                    $.ajax({
                        type: 'post',
                        {{--url: '/{{config('constant.name_admin')}}/sampleInfo/indexInfoLuru',--}}
                        url: '/{{config('constant.name_admin')}}/photo/list/sub',
                        // dataType: 'json',
                        data: {
                            detail_id: id,
                            non_photo: base64data,
                            _token: '{{ csrf_token() }}',
                            _form_token: '{{ csrf_form_token() }}',
                        },
                        success: function (data) {
                            // console.log(data);
                            if (data === '1') {
                                let img = '<div><img style="width:100%;" class="img-responsive radio" src="' + base64data + '" onclick="biggerimg(this)"> ' +
                                    '<a onclick="imgdel(' + bar_code + ',this)" class="ml-5 btn btn-danger-outline radius size-MINI">删除</a></div>';
                                $('#non-photo-' + id).html(img)
                                layer.msg('图片上传成功!', {icon: 1, time: 1000},function (){
                                    window.location.reload()
                                });
                                layer.close(index);

                            } else {
                                layer.msg(data.msg ? data.msg : '图片上传失败!', {icon: 2, time: 2000},function (){
                                    window.location.reload()
                                });
                            }
                        },
                        error: function (data) {
                            ajax_error(data);
                        },
                        beforeSend: function () {
                            //0.4透明度 白色遮罩
                            index2 = layer.load(2, {shade: [0.05, '#000']});
                        },
                        complete: function () {
                            layer.close(index2);
                        },
                    });
                },
                cancel: function () {
                    //右上角关闭回调
                }
            });
        }

        function upimg() {
            $(this).on('change', function (e) {
                var file = e.target.files[0],//拿到原始对象
                    thisType = file.type,//获取到表面的名称，可判断文件类型
                    reader = new FileReader(),
                    img = e.target.nextSibling;
                if (thisType.indexOf('image/') !== 0) {
                    layer.alert('该文件不是图片！');
                    return false;
                }
                if (file.size > 500 * 1024) {
                    //调用函数,对图片进行压缩
                    compressimg(file, function (imgBase64) {
                        $(img).attr('src', imgBase64);
                    })
                }
                //readAsDataURL(file),读取文件，将文件以数据URL的形式保存在result的属性中
                reader.readAsDataURL(file);
                //文件加载成功以后，渲染到页面
                reader.onload = function (e) {
                    $('.fornonphoto').attr('src', e.target.result).load(function () {/*如果要获取图片的真实的宽度和高度有三点必须注意1、需要创建一个image对象：如这里的$("")2、指定图片的src路径3、一定要在图片加载完成后执行如.load()函数里执行*/
                        let realWidth = this.width, realHeight = this.height, bili = (realHeight / realWidth).toFixed(2);//如果真实的宽度大于浏览器的宽度就按照100%显示
                        if ((bili < 0.77 && bili > 0.73) || (bili < 1.35 && bili > 1.31)) {
                            isup = 1;
                        } else {
                            layer.msg('图片不符合要求');
                            isup = 0;
                            return false;
                        }
                    })
                }
            })
        }

        function imgdel(bar_code, e) {
            $.ajax({
                type: 'get',
                url: '/{{config('constant.name_admin')}}/sampleinfo/imgdeal/non_photo/del/' + bar_code,
                success: function (data) {
                    if (data === '1') {
                        $(e).parent().html(nophonotext);
                        layer.msg('删除成功!', {icon: 1, time: 1000});
                    } else {
                        layer.msg('删除失败!', {icon: 2, time: 2000});
                    }
                },
                error: function (data) {
                    ajax_error(data);
                },
                beforeSend: function () {
                    //0.4透明度 白色遮罩
                    index2 = layer.load(2, {shade: [0.05, '#000']});
                },
                complete: function () {
                    layer.close(index2);
                },
            });
        }

        /*查看驳回原因*/
        function show_baklog(id) {
            let url = '/{{config('constant.name_admin')}}/sampleinfo/rejectLog/0/' + id;
            layer_show('驳回原因', url, 500, 400);
        }
        /*下载原始记录*/
        function download_original(id,is_batch=0) {
            if (is_batch == 0) {
                window.open('/{{config('constant.name_admin')}}/exportReport/origin?id=' + id, '_blank');
            }else{
                window.open('/{{config('constant.name_admin')}}/exportReport/origin?contract_id=' + id, '_blank');
            }

        }

    </script>
@endsection
